<template>
  <div>
     <el-form  :inline="true">
       <template v-for="(item, index) in selectList" >
         <template v-if="item.type === 'ReportDate'">
<!--           <div>-->
             <common-select
                 :key="index"
                 :key-field="item.keyField"
                 :show-field="item.keyField"
                 :val-field="item.keyField"
                 :list="item.list"
                 :placeholder="item.placeholder"
                 v-model="form.timeType"/>
             <el-date-picker
                 v-model="form.type"
                 type="daterange"
                 range-separator="至"
                 start-placeholder="开始日期"
                 end-placeholder="结束日期">
             </el-date-picker>
<!--           </div>-->
         </template>
         <template v-else-if="item.type === 'Input'" >
            <el-input v-model="form[item.formKey]" style='width:400px' :placeholder="item.placeholder"></el-input>
         </template>
         <template v-else>
<!--           style='width:140px'-->
           <common-select
               :filterable="true"
               :key="index"
               :key-field="item.value || 'value'"
               :show-field="item.name || 'name'"
               :val-field="item.value  || 'value'"
               :list="item.list"
               :placeholder="item.placeholder"
               v-model="form[item.formKey]"/>
         </template>
       </template>
     </el-form>
  </div>
</template>
<script>


  const timeTypeArray = [
    {value: '1', name: '报备时间'},
    {value: '2', name: '到访时间'},
    {value: '3', name: '认筹时间'},
    {value: '4', name: '认购时间'},
    {value: '5', name: '签约时间'},
    {value: '6', name: '交易失败时间'}
  ]
  const reportUserTypeList = [
    {value: '1', name: '案场代报备'},
    {value: '2', name: '经纪人报备'}
  ]
  const visitStatusList = [
    // {value: '', name: '全部到场状态'},
    {value: '1', name: '单次到访'},
    {value: '3', name: '多次到访'},
  ]
  const payFinishList = [
    // {value: '', name: '不限'},
    {value: '0', name: '未交齐'},
    {value: '1', name: '已交齐'},
  ]
  import CommonSelect from "../../common/CommonSelect.vue";
  import { Service } from "../../../js/base"
  export default {
    name: "ReportSearch",
    components: {
      CommonSelect
    },
    props: {
      value: {
        type: Object,
        default: () => {
          return {}
        }
      },
    },
    data () {
      return {
        form: this.value,
        searchParams: {
              orgId:'',
              storeId:''
        },
        selectList: [
          {  placeholder: '全部楼盘', value: 'id',  name: 'name',  list: [], formKey: 'premisesId',   },
          {  placeholder: '全部报备类型', list: reportUserTypeList, formKey: 'reportUserType',  },
          {  placeholder: '全部分销公司', value: 'agentCompany', name: 'agentCompanyName',  list: [], formKey: 'companyId', },
          {  placeholder: '全部分销部门', value: 'id', name: 'departmentName',  list: [], formKey: 'agencyDeptId', },
          // {  placeholder: '全部分销门店', value: 'id', name: 'departmentName',  list: [], formKey: 'storeOrGroupId',   },
          // {  placeholder: '全部分销组别', value: 'id', name: 'departmentName',  list: [], formKey: 'groupId',   },
          {  placeholder: '全部分销经纪人', value: 'id', name: 'accountName',  list: [], formKey: 'agentId',   },
          {  placeholder: '全部报备状态', list: [],  formKey: 'customerStatus',  },
          {  placeholder: '全部交易状态', list: [],  formKey: 'confirmStatus',  },
          {  placeholder: '全部到访状态', list: visitStatusList, formKey: 'visitState', },
          {  placeholder: '全部推荐人', value: 'recommenderId', name: 'userName',  list: [], formKey: 'recommenderId',  },
          {  placeholder: '报备时间', value: 'type',  list: timeTypeArray, formKey: 'reportDate',  type: 'ReportDate' },
          {  placeholder: '客户姓名、电话号码',value: '',name: '',  list: [], formKey: 'name',   type: "Input"},
          {  placeholder: '全部按揭状态', list: [],  formKey: 'mortgageStatus',  },
          {  placeholder: '全部首付交齐状态', list: payFinishList,  formKey: 'payFinish',  },
        ]
      }
    },
    mounted() {
      this.init()
    },
    methods: {
      init() {
        this.customerStatuList()
        this.getPremiseList()
        this.agentOrgList()
        this.getrecommendersList()
        this.confirmStatuList()
        this.mortgageStatusList()
      },
      /**
       * 更新form list
       */
      updateFormList(key = '', list = []) {
        const index = this.selectList.findIndex(item => item.formKey === key)
        if(index > -1) {
          this.selectList[index].list = list
        }
      },
      //楼盘
      getPremiseList() {
        const url =  this.utilHelper.apiUrl+"/api/getPremisesListForPartner";
        const body = {};
       body.params = {
            userId: window.localStorage.getItem("userId")
        };
        this.$http.post(url, body).then((response) => {
          const resData = response.body.resData
          //if(response.body.result == '1') {
          this.updateFormList('premisesId', resData && resData.inPremisesList)
          //}
        })
      },
      customerStatuList() {
        const _self = this;
        const url = this.utilHelper.apiUrl + '/common/getEnum/CustomerStatusEnum';
        _self.$http.get(url, {}).then((response) => {
          this.updateFormList('customerStatus')
          var resData = response.body.data;
          if(resData) {
            let tmpList = []
            for(let key in resData) {
              tmpList.push({
                value: key,
                name: resData[key]
              })
            }
            this.updateFormList('customerStatus', tmpList)
          }
        });
      },
      //推荐人
      getrecommendersList() {
        const url =  this.utilHelper.apiUrl+"/api/premises/recommenders/all/list";
        const body = {};
        body.params = {
          id: '1'
        };
        this.$http.post(url, body).then((response) => {
          if(response.body.result == '1') {
            this.updateFormList('recommenderId', response.body.resData.list)
          }
        })
      },
      /**
       * 获取分销机构列表
       */
      agentOrgList() {
        const _self = this;
        const url = this.utilHelper.apiUrl + '/api/getAgentOrgByDevOrg';// '/api/getAgentOrgByDevOrg';
        var body = {};
        body.params = {
            userId: window.localStorage.getItem("userId")
        };
        this.updateFormList('companyId')
        _self.$http.post(url, body).then((response) => {
          const res = response.body.resData;
          if (res.result == '0') {
            layer.alert(res.errorMsg);
          } else {
            this.updateFormList('companyId', res.agentOrgList)
          }
        });
      },
      findDeptList(orgId){
        var _self = this;
        var url = this.utilHelper.apiUrl + "/api/agencyreport/getAgencyDept";
        var body = {};
        body.params = {
          agentCompany: orgId,
        };
        this.updateFormList('agencyDeptId')
        _self.$http.post(url, body).then((response) => {
          let agencyDeptList = response.body.resData.list;
          for (var ii = 0; ii < agencyDeptList.length; ii++) {
            let dept = agencyDeptList[ii];
            if (dept.layer && dept.layer > 0) {
              let space = "";
              for (let jj = 0; jj < dept.layer; jj++) {
                space += "　";
              }
              dept.departmentName = space + dept.departmentName;
            }
          }
          this.updateFormList('agencyDeptId', agencyDeptList)
        });
      },
      /**
       * 获取分销机构查门店列表
       */
      findStoreList(orgId, storeId){
        var _self = this;
        var url = this.utilHelper.apiUrl + "/api/getStoreByOrg";
        if (!orgId) {
          this.updateFormList('storeOrGroupId')
          this.updateFormList('agentId')
          return false;
        }
        var body = {};
        body.params = {
            userId: window.localStorage.getItem("userId"),
            merchantId: orgId,
            storeId: storeId
        };
        _self.$http.post(url, body).then((response) => {
            if( response && response.body && response.body.resData && response.body.resData.list){
              if (storeId){
                this.updateFormList('groupId',  response.body.resData.list)
              }else {
                this.updateFormList('agentId',  [])
                this.updateFormList('groupId',  [])
                this.updateFormList('storeOrGroupId',  response.body.resData.list)
              }
            }else{
              this.updateFormList('storeOrGroupId')
              this.updateFormList('groupId')
            }

        });
      },
      /**
       * 获取经纪人列表
       * @param deptId
       * @returns {boolean}
       */
      partnerList(deptId) {
        const _self = this;
        // this.updateFormData({ // 门店重置
        //   storeOrGroup: '',
        //   agentId: ''
        // })
        if (deptId == "") {
          this.updateFormList('agentId')
          this.updateFormList('storeOrGroupId')
          return false;
        }
        const url = this.utilHelper.apiUrl + '/api/getPartnerInfoByDept';//'/api/getPartnerByCompany';
        const body = {
          'params': {
            'deptId': deptId
          }
        };
        this.$http.post(url, body).then((response) => {
          const res = response.body;
          if (res && res.result == '1') {
            this.updateFormList('agentId', res.resData && res.resData.partnerList || [])
          } else {
            layer.alert('获取经纪人失败');
          }
        });
      },
      /**
       * 获取交易状态
       */
      confirmStatuList() {
        const _self = this;
        const url = this.utilHelper.apiUrl + '/common/getEnum/ConfirmStatusEnum';
        _self.$http.get(url, {}).then((response) => {
          let tmpList = []
          var resData = response.body.data;
          for(let key in resData) {
            tmpList.push({
              value: key,
              name: resData[key]
            })
          }
          this.updateFormList('confirmStatus', tmpList)
        });
      },
      mortgageStatusList() {
        const _self = this;
        const url = this.utilHelper.apiUrl + '/common/getEnum/MortgageStatusEnum';
        _self.$http.get(url, {}).then((response) => {
          let tmpList = []
          var resData = response.body.data;
          for(let key in resData) {
            tmpList.push({
              value: key,
              name: resData[key]
            })
          }
          this.updateFormList('mortgageStatus', tmpList)
        });
      },
    },
    watch: {
      'form.companyId': {
        handler(val, newVal) {
          if(val) {
            // 清空门店和组别信息
            this.findStoreList(val)
            this.findDeptList(val)
            this.form.storeOrGroupId = ''
            this.form.agencyDeptId = ''
            this.form.groupId = ''
            this.form.agentId = ''
          }
        }
      },
      'form.agencyDeptId': {
        handler(val, newVal) {
          var _this = this;
          if(val) {
            this.partnerList(val)
            this.form.groupId = ''
            this.form.agentId = ''
          }
        }
      },
      'form.storeOrGroupId': {
        handler(val, newVal) {
          var _this = this;
          if(val) {
            //同时要加载组别信息
            this.findStoreList(_this.form.companyId, val)
            this.partnerList(val)
            this.form.groupId = ''
            this.form.agentId = ''
          }
        }
      },
      'form.groupId': {
        handler(val, newVal) {
          if(val) {
            // 加载信息
            this.partnerList(val)
            this.form.agentId = ''
          }
        }
      }
    }
  }
</script>

<style scoped>

</style>
